<?php
session_start();
//start the session
$message=null;


//Create a database connection
require('config/mysql.config.inc');
$mysqli = new mysqli($host, $username, $password, $db);	


//FUNCTION: valid_email(string: email address) {
function valid_email($email) {
	//check if the email address provided is a valid email address (how?)
	//if so return true, else return false
	$pattern = "/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/";
	return preg_match($pattern, $email);
}

//FUNCTION: valid_zip(string: zip code) {
function valid_zip($zip) {
	//check if the zipcode provided is a valid zip code
	//if so return true, else return false
	$pattern = "/^[0-9]{5}$/";
	return preg_match($pattern, $zip);
}

//FUNCTION: valid_phone(string: phone) {
function valid_phone($phone) {
	//check if the phone provided is a valid phone number
	//if so return true, else return false
	$pattern = "/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/";
	return preg_match($pattern, $phone);
}

//FUNCTION: username_unique(string: username)
function username_unique($email) {
	require('config/mysql.config.inc');
	$mysqli = new mysqli($host, $username, $password, $db);	
	$query = "SELECT email FROM Users WHERE email = '" . $email . "';";
	$result = $mysqli->query($query);
	$numrows = $result->num_rows;
	return ($numrows == 0);
}

//if create account form was submitted, process the results and add them to the Users relation
	//if all the submitted data is correct
	//are required fields are set
	if (isset($_POST['form']) && $_POST['form']==1 && isset($_POST['password']) && isset($_POST['password2']) && isset($_POST['email'])) {
		//are password fields equal? is email a valid email address? is username taken?
		if ($_POST['password'] == $_POST['password2'] && valid_email($_POST['email']) && username_unique($_POST['email'])) {
	
			if(isset($_POST['city'])){$city = $_POST['city'];}else{$city = " ";}
			if(isset($_POST['state'])){$state = $_POST['state'];}else{$state = " ";}
			if(isset($_POST['zip'])) {
				$zip= " ";
				if ($_POST['zip']!="") {
					if (valid_zip($_POST['zip'])) {
						$zip = $_POST['zip'];
					} else {
						$zip = " ";
						$message.=" The zipcode you entered was invalid. ";
					}
				}
			}else{
				$zip = " ";
			}
			if(isset($_POST['fname'])){$fname = $_POST['fname'];}else{$fname = " ";}
			if(isset($_POST['lname'])){$lname = $_POST['lname'];}else{$lname = " ";}
			if(isset($_POST['phone'])) {
				$phone= " ";
				if ($_POST['phone']!="") {
					if (valid_phone($_POST['phone'])) {
						$phone = $_POST['phone'];
					} else {
						$phone = " ";
						$message.=" The phone number you entered was invalid. ";
					}
				}
			}else{
				$phone = " ";
			}
			
			//hash the password
			$password= hash("sha256", $_POST['password']);
			$email = $_POST['email'];
			//print(username_unique($email));
			if(username_unique($email)){		
				//Create a query from the POSTed data
				$query = "INSERT into Users (email, hashpwd, city, state, zip, firstname, lastname, telephone) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
				$stmt= $mysqli->stmt_init();
				if($stmt->prepare($query)){
					$stmt->bind_param('ssssssss', $email, $password, $city, $state, $zip, $fname, $lname, $phone);
					if($stmt->execute()){
						$_SESSION['user']= $_POST['email'];
						$message="Log in was successful!";
					}
					else{
						$message= "Error: User not created. Please try again.";
					}
				}				
			}

		} 
		else {
			//form are set, but something is wrong with the input data
			
			if (!($_POST['password'] == $_POST['password2'])){
				$message=$message. "The two password fields don't match. Please go back and correct them.<br/>";
			}
			
			if (!valid_email($_POST['email'])) {
				$message=$message. "Your email address is not valid. Please go back and enter a correct one.<br/>";
			}
			if (!username_unique($_POST['email'])) {
				$message=$message. "Sorry, the username you requested has already been taken. Please go back and enter another one.<br/>";
			}
		}
	} 
	else {
		if (isset($_POST['form']) && $_POST['form']==1){ // user was trying to create an account
			//and not all required fields were set
			
			$message=$message. " Oops, you forgot to fill in all required fields. Make sure username, both password fields, and email are filled in.<br/>";
		}
	}
	
//if login form was submitted, process the results
if (isset($_POST['form']) && $_POST['form']==2 && isset($_POST['password']) && isset($_POST['email'])){
	//return that user's row from the Users relation
	//hash the password
	$password= hash("sha256", $_POST['password']);

	//Create a query from the POSTed data
	$query = "SELECT * FROM Users WHERE email = ?";
	$stmt= $mysqli->stmt_init();
	if($stmt->prepare($query)){
		$stmt->bind_param('s', $_POST['email']);
		$stmt->execute();
		$stmt->bind_result($one, $two, $three, $four, $five, $six, $seven, $eight, $nine);
		while($stmt->fetch()){
			$uid= $one;
			$pw= $nine;
		}
	}
	
	//if stmt->fetch returned a uid and hashed passwords match
	if (isset($uid)) {
		if($password == $pw){
			//log in user
			$_SESSION['user']= $_POST['email'];
			$message=$message."Log in was successful!<br/>";
		}
		else{
			$message=$message."Incorrect Password. Please Try Again!<br/>";
		}
	}
	else{
		$message=$message."Username not recognized. Please Try Again!<br/>";
		//error logging in. process error results
	}
}
elseif(!isset($_SESSION['user']) && (isset($_POST['form']) && $_POST['form'] == 2)){
	$message=$message."There was an error logging in. Please Try Again!<br/>";
}


//if edit account form was submitted, process the results
if (isset($_POST['form']) && $_POST['form']==3 && isset($_POST['password'])){
	//if updating password
	$passwordSet=false;
	if (isset($_POST['new_password']) && isset($_POST['password2'])) {
		//are password fields equal?
		if ($_POST['new_password']!="" || $_POST['password2']!="") {
			if ($_POST['new_password'] == $_POST['password2']) {
				$passwordSet=true;
				//hash the password
				$password= hash("sha256", $_POST['password']);

				//Create a query from the POSTed data
				$query = "SELECT * FROM Users WHERE email = ? AND hashpwd = ?";
				$stmt= $mysqli->stmt_init();
				if($stmt->prepare($query)){
					$stmt->bind_param('ss', $_SESSION['user'], $password);
					$stmt->execute();
					$stmt->bind_result($one, $two, $three, $four, $five, $six, $seven, $eight, $nine);
					while($stmt->fetch()){
						$uid= $one;
						$pw= $nine;
					}
				}
				
				//submit query
				//$result = $mysqli->query($query);
				
				//if $uid is set and hashed passwords match
				if (isset($uid)) {
					if($password == $pw){
						//print $_POST['new_password'];
						$query = "UPDATE Users SET hashpwd = ? WHERE email = ?";
						$stmt= $mysqli->stmt_init();
						if($stmt->prepare($query)){
							$password= hash("sha256", $_POST['new_password']);
							$stmt->bind_param('ss', $password, $_SESSION['user']);
							$stmt->execute();
						}
						//Let user know whether new password was successful
						if(!$stmt->execute()){							
							$message.="Error: password did not update.";
						}	
						else{
							$message.="Password updated successfully! ";
						}
					}else {
						$message.="Old Password is incorrect.";
					}
				}
			} else {
				$message.="New Password fields do not match.";
			}
		}
	}
	
	
			if(isset($_POST['city'])){$city = $_POST['city'];}else{$city = " ";}
			if(isset($_POST['state'])){$state = $_POST['state'];}else{$state = " ";}
			if(isset($_POST['zip'])) {
				if ($_POST['zip']!="") {
					if (valid_zip($_POST['zip'])) {
						$zip = $_POST['zip'];
					} else {
						$zip = " ";
						$message.=" The zipcode you entered was invalid. ";
					}
				}
			}else{
				$zip = " ";
			}
			if(isset($_POST['fname'])){$fname = $_POST['fname'];}else{$fname = " ";}
			if(isset($_POST['lname'])){$lname = $_POST['lname'];}else{$lname = " ";}
			if(isset($_POST['phone'])) {
				if ($_POST['phone']!="") {
					if (valid_phone($_POST['phone'])) {
						$phone = $_POST['phone'];
					} else {
						$phone = " ";
						$message.=" The phone number you entered was invalid. ";
					}
				}
			}else{
				$phone = " ";
			}
	//update the user's row in Users
	$password= hash("sha256", $_POST['password']);
	//Create a query from the POSTed data
	if($_POST['password'] != ""){
		if (!($passwordSet)){
			//hash the password
			$password= hash("sha256", $_POST['password']);

			//Create a query from the POSTed data
			$query = "SELECT * FROM Users WHERE email = ?";
			$stmt= $mysqli->stmt_init();
			if($stmt->prepare($query)){
				$stmt->bind_param('s', $_SESSION['user']);
				$stmt->execute();
				$stmt->bind_result($one, $two, $three, $four, $five, $six, $seven, $eight, $nine);
				while($stmt->fetch()){
					$uid= $one;
					$pw= $nine;
				}
			}
			
			//if $uid is set and hashed passwords match
			if (isset($uid)) {
				if($password == $pw){
					if($state != "NONE"){
						$query = "UPDATE Users SET zip = ?, city= ?, state = ?, telephone= ?, firstname= ?, lastname= ? WHERE email= ?";
						$stmt=$mysqli->stmt_init();
						if($stmt->prepare($query)){
							$stmt->bind_param('sssssss', $zip, $city, $state, $phone, $fname, $lname, $_SESSION['user']);
							$stmt->execute();
						}
	
					}
					else{
						$query = "UPDATE Users SET zip = ?, city = ?, telephone = ?, firstname = ?, lastname = ? WHERE email= ?";
						$stmt=$mysqli->stmt_init();
						if($stmt->prepare($query)){
							$stmt->bind_param('ssssss', $zip, $city, $phone, $fname, $lname, $_SESSION['user']);
							$stmt->execute();
						}
					}
					//let him know if successful or not
					if(!$stmt->execute()){
						//printf("Errormessage: %s\n", $mysqli->error);								
						$message.="Error: personal information did not update.";
					}
					else{
						$message.=" Successfully updated personal information!";
					}
				} 
			} else {
				$message.=" Password incorrect. ";
			}
		}
	}
	else{
		$message.="Please Enter Your Password Before Updating Information.";
		
	}
}
//Logout user
//this code will be changed later, but suffices for a simple logout form	
if (isset($_GET['logout'])) {
	if(isset($_SESSION['user'])){
		$olduser = $_SESSION['user'];
		unset($_SESSION['user']);
		session_destroy();
		$olduser = false;
		$message=$message. " You have logged out.";
	}
}	
	
//Check sessions to see if user is logged in or not
$logged=false;
if (isset($_SESSION['user'])){
	$logged=true;
}

	$page= 'Account';
	include ('includes/header.php');	
	include('includes/menubar.php');
	print("\n");
?>

<div class="body_content">
<?php
print("<p class=\"message\">$message</p>");


//if logged in
if ($logged){
	//Manage Wishlists
		//link to wishlists page (perhaps list current wishlists for linking purposes?)
	//Edit Account Info
		//create a form to add/edit this users account info (enter current password to validate)
		//query the database to prefill the form entries
		
		
		
		//PROBABLY NOT NEEDED?
		/*

		$user= $_SESSION['user'];
		$query= ("SELECT * FROM Users WHERE email = '".$user."'");
		$result= $mysqli->query($query);
		$userinfo= $result->fetch_assoc();
		*/

?>	
	<span class="underline"><strong>Edit Account</strong></span>
	<form action="useracct.php" method="post">
		<fieldset>
			Current Password: <input type="password" name="password" size="12" />*
			<br/><br/><br/>
			<strong>Edit Your Account Details:</strong><br/>
			New Password: <input type="password" name="new_password" size="12" /><br/>
			Confirm New Password: <input type="password" name="password2"  size="12" /><br/>
			Email Address: <?php			
				if (isset($_SESSION['user'])){
					$email= $_SESSION['user'];	
					//display the email address
					print("$email");				
				} 
				
				print("<input type=\"hidden\" name=\"email\" value=\"$email\"/>");
				?>
			<br/><br/>
			<strong>Edit Your Personal Details:</strong><br/>
			First Name: <input type="text" value="<?php	
					require('config/mysql.config.inc');
					$mysqli = new mysqli($host, $username, $password, $db);	
					$query = "SELECT firstname from Users where email = '" . $_SESSION['user'] . "';";	
					$result = $mysqli->query($query);
					if($result->num_rows == 0){
						//$message = $message . "Error Message: Database Error";
						print "";
					}
					else{
						$ans = $result->fetch_assoc();
						$firstname = $ans["firstname"];
						print $firstname;
					}
				?>" name="fname" size="20" />
			Last Name: <input type="text" value="<?php	
						require('config/mysql.config.inc');
						$mysqli = new mysqli($host, $username, $password, $db);	
						$query = "SELECT lastname from Users where email = '" . $_SESSION['user'] . "';";	
						$result = $mysqli->query($query);
						if($result->num_rows == 0){
							//$message = $message . "Error Message: Database Error";
							print "";
						}
						else{
							$ans = $result->fetch_assoc();
							$lastname = $ans["lastname"];
							print $lastname;
						}
					?>" name="lname" size="20" /><br/>
			City: <input type="text" value="<?php	
							require('config/mysql.config.inc');
							$mysqli = new mysqli($host, $username, $password, $db);	
							$query = "SELECT city from Users where email = '" . $_SESSION['user'] . "';";	
							$result = $mysqli->query($query);
							if($result->num_rows == 0){
								//$message = $message . "Error Message: Database Error";
								print "";
							}
							else{
								$ans = $result->fetch_assoc();
								$city = $ans["city"];
								print $city;
							}
						?>" name="city" size="20" />
			State: 		<?php	
										require('config/mysql.config.inc');
										$mysqli = new mysqli($host, $username, $password, $db);	
										$query = "SELECT state from Users where email = '" . $_SESSION['user'] . "';";	
										$result = $mysqli->query($query);
										if($result->num_rows == 0){
											//$message = $message . "Error Message: Database Error";
											print "";
										}
										else{
											$ans = $result->fetch_assoc();
											$state = $ans["state"];
											print $state;
										}
							?>
						<select name="state">
						<option value="NONE">--</option>
						<option value="AL">AL</option>
						<option value="AK">AK</option>
						<option value="AZ">AZ</option>
						<option value="AR">AR</option>
						<option value="CA">CA</option>
						<option value="CO">CO</option>
						<option value="CT">CT</option>
						<option value="DE">DE</option>
						<option value="DC">DC</option>
						<option value="FL">FL</option>
						<option value="GA">GA</option>
						<option value="HI">HI</option>
						<option value="ID">ID</option>
						<option value="IL">IL</option>
						<option value="IN">IN</option>
						<option value="IA">IA</option>
						<option value="KS">KS</option>
						<option value="KY">KY</option>
						<option value="LA">LA</option>
						<option value="ME">ME</option>
						<option value="MD">MD</option>
						<option value="MA">MA</option>
						<option value="MI">MI</option>
						<option value="MN">MN</option>
						<option value="MS">MS</option>
						<option value="MO">MO</option>
						<option value="MT">MT</option>
						<option value="NE">NE</option>
						<option value="NV">NV</option>
						<option value="NH">NH</option>
						<option value="NJ">NJ</option>
						<option value="NM">NM</option>
						<option value="NY">NY</option>
						<option value="NC">NC</option>
						<option value="ND">ND</option>
						<option value="OH">OH</option>
						<option value="OK">OK</option>
						<option value="OR">OR</option>
						<option value="PA">PA</option>
						<option value="RI">RI</option>
						<option value="SC">SC</option>
						<option value="SD">SD</option>
						<option value="TN">TN</option>
						<option value="TX">TX</option>
						<option value="UT">UT</option>
						<option value="VT">VT</option>
						<option value="VA">VA</option>
						<option value="WA">WA</option>
						<option value="WV">WV</option>
						<option value="WI">WI</option>
						<option value="WY">WY</option>
					</select><br/>
			Zip: <input type="text" value="<?php	
							require('config/mysql.config.inc');
							$mysqli = new mysqli($host, $username, $password, $db);	
							$query = "SELECT zip from Users where email = '" . $_SESSION['user'] . "';";	
							$result = $mysqli->query($query);
							if($result->num_rows == 0){
								//$message = $message . "Error Message: Database Error";
								print "";
							}
							else{
								$ans = $result->fetch_assoc();
								$zip = $ans["zip"];
								print $zip;
							}
						?>" name="zip" size="6" /><br/>
			Phone: <input type="text" value="<?php	
								require('config/mysql.config.inc');
								$mysqli = new mysqli($host, $username, $password, $db);	
								$query = "SELECT telephone from Users where email = '" . $_SESSION['user'] . "';";	
								$result = $mysqli->query($query);
								if($result->num_rows == 0){
									//$message = $message . "Error Message: Database Error";
									print "";
								}
								else{
									$ans = $result->fetch_assoc();
									$phone = $ans["telephone"];
									print $phone;
								}
							?>" name="phone" size="15" />(123-456-7890)<br/>
			<br/><span class="small">*Don't forget to enter your password above before you submit the form!</span><br/>
			<input type="hidden" name="form" value="3"/>
			<input type="submit" name="create_button" value="Edit Account" />
		</fieldset>
	</form>
	
	
<?php	
} else { //if not logged in
	//Log in Form
		//username/password input form
	//Create Account Form
		//choose username and password - two password forms to confirm
		//first name, last name, email*, city, state, zip, telephone
?>
	<strong>Have an account? Log in</strong>
	<form action="useracct.php" method="post">
		<fieldset>
			Email: <input type="text" name="email" size="20" />
			Password: <input type="password" name="password" size="12" />
			<input type="hidden" name="form" value="2"/>
			<input type="submit" name="login_button" value="Log In" />
		</fieldset>
	</form>

	<strong>Create Account</strong>
	<form action="useracct.php" method="post">
		<fieldset>
		<!-- Eventually use AJAX to display a message if user has left required field blank? -->
			Enter your email address: <input type="text" name="email" size="20" />*<br/>
			Choose a password: <input type="password" name="password" size="12" />*<br/>
			Confirm your password: <input type="password" name="password2" size="12" />*<br/>
			<br/>
			<strong>The following information will be required if you wish to place orders:</strong><br/>			
			Enter your first name: <input type="text" name="fname" size="12" /><br/>
			Enter your last name: <input type="text" name="lname" size="12" /><br/>
			City: <input type="text" name="city" size="12" />
			State: <select name="state">
						<option></option>
						<option value="AL">AL</option>
						<option value="AK">AK</option>
						<option value="AZ">AZ</option>
						<option value="AR">AR</option>
						<option value="CA">CA</option>
						<option value="CO">CO</option>
						<option value="CT">CT</option>
						<option value="DE">DE</option>
						<option value="DC">DC</option>
						<option value="FL">FL</option>
						<option value="GA">GA</option>
						<option value="HI">HI</option>
						<option value="ID">ID</option>
						<option value="IL">IL</option>
						<option value="IN">IN</option>
						<option value="IA">IA</option>
						<option value="KS">KS</option>
						<option value="KY">KY</option>
						<option value="LA">LA</option>
						<option value="ME">ME</option>
						<option value="MD">MD</option>
						<option value="MA">MA</option>
						<option value="MI">MI</option>
						<option value="MN">MN</option>
						<option value="MS">MS</option>
						<option value="MO">MO</option>
						<option value="MT">MT</option>
						<option value="NE">NE</option>
						<option value="NV">NV</option>
						<option value="NH">NH</option>
						<option value="NJ">NJ</option>
						<option value="NM">NM</option>
						<option value="NY">NY</option>
						<option value="NC">NC</option>
						<option value="ND">ND</option>
						<option value="OH">OH</option>
						<option value="OK">OK</option>
						<option value="OR">OR</option>
						<option value="PA">PA</option>
						<option value="RI">RI</option>
						<option value="SC">SC</option>
						<option value="SD">SD</option>
						<option value="TN">TN</option>
						<option value="TX">TX</option>
						<option value="UT">UT</option>
						<option value="VT">VT</option>
						<option value="VA">VA</option>
						<option value="WA">WA</option>
						<option value="WV">WV</option>
						<option value="WI">WI</option>
						<option value="WY">WY</option>
					</select><br/>
			Zip Code: <input type="text" name="zip" size="6" /><br/>
			Phone: <input type="text" name="phone" size="12" /> (123-456-7890)<br/>
			<input type="hidden" name="form" value="1"/>
			<input type="submit" name="create_button" value="Create Account" />
		</fieldset>
	</form>

<?php
} //end the else
echo '</div>';
include ('includes/footer.php');

//close the database connection
$mysqli->close();
?>

</body>
</html>	